<!--备料分析-->
<template>
  <basic-container>
    <avue-crud
      :option="option"
      @tree-load="treeLoad"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menuLeft">
        <el-button icon="el-icon-plus" type="primary" size="small" @click.stop="handleAdd">新增</el-button>
        <!--
        <el-button icon="el-icon-s-promotion" @click.stop="handleOutBound()" type="success" size="small">出库</el-button> -->
        <el-button type="warning" size="small" icon="el-icon-download" @click="$refs.exportComp.visible = true">导出</el-button>
      </template>
      <!-- TODO: 待拣货 才允许拆分 -->
      <template slot-scope="{ row }" slot="menu">
        <el-button type="text" icon="el-icon-scissors" size="small" plain style="border: 0 !important" v-if="!row.isSplit && !row.isLeaf" @click.stop="handleSplit(row)">
          拆分
        </el-button>
        <el-button type="text" icon="el-icon-view" size="small" plain style="border: 0 !important" @click.stop="handleView(row)">详情</el-button>
        <el-button type="text" icon="el-icon-printer" size="small" plain style="border: 0 !important" @click.stop="handlePrint(row)">打印</el-button>
      </template>
      <template slot-scope="{ row, index }" slot="completeAnalysisCh">
        <span v-if="row.completeAnalysisCh == '欠料'" style="color: red">欠料</span>
        <span v-else>齐料</span>
      </template>
    </avue-crud>
    <!-- 备料规则配置 -->
    <el-dialog
      custom-class="ruleDialog"
      append-to-body
      :close-on-click-modal="false"
      title="备料规则配置"
      :visible.sync="preMaterialRuleDialog.visible"
      v-if="preMaterialRuleDialog.visible"
      width="40%"
      top="7vh"
    >
      <el-tabs v-model="preMaterialRuleDialog.activeName" type="card">
        <el-tab-pane label="备料分析配置" name="first" v-if="preMaterialRuleType != 'split'">
          <div class="item">
            <el-checkbox v-model="preMaterialRuleDialog.form.isFifo" :disabled="true">先进先出</el-checkbox>
            <el-tooltip class="item" effect="dark" content="启用后则强控按先进先出的推荐批次出库" placement="top-start">
              <i class="header-icon el-icon-info"></i>
            </el-tooltip>
          </div>
          <div class="item">
            <div class="specifyAnalysis">
              <el-checkbox v-model="preMaterialRuleDialog.form.isSpecifyAnalysis" :disabled="false" @change="handleChangeSpecifyAnalysis">指定分析物料类别</el-checkbox>
              <el-tooltip class="item" effect="dark" content="指定某些物料类别，备料分析只分析指定的物料类别，非指定物料则不进行备料分析，全部都是欠料！" placement="top-start">
                <i class="header-icon el-icon-info"></i>
              </el-tooltip>
              <el-button class="addMaterialBtn" type="primary" size="mini" v-if="preMaterialRuleDialog.form.isSpecifyAnalysis" @click="handleAddMaterial">+添加物料</el-button>
            </div>

            <!-- <el-input
              type="textarea"
              v-if="preMaterialRuleDialog.form.isSpecifyAnalysis"
              :autosize="{ minRows: 5 }"
              clearable
              v-model="preMaterialRuleDialog.form.specifyMaterialCategoryCodes"
            >
            </el-input> -->
            <!-- {{ preMaterialRuleDialog.form.specifyMaterialCategoryAnalysisList }} -->

            <avue-select
              style="width: 100%"
              multiple
              clearable="false"
              class="specifyMaterialCategoryAnalysisSelect"
              popper-class="el-select_popperClass"
              v-model="preMaterialRuleDialog.form.specifyMaterialCategoryCodes"
              :dic="preMaterialRuleDialog.form.specifyMaterialCategoryAnalysisList"
              @change="handleSpecifyMaterialCategoryDelete($event)"
              readonly="true"
            ></avue-select>
          </div>
        </el-tab-pane>
        <el-tab-pane label="拆分备料单规则" name="second" v-if="preMaterialRuleType != 'add' && preMaterialRuleType != 'edit'">
          <el-row class="ruleRowForm">
            <el-radio v-model="preMaterialRuleDialog.form.splitType" border label="WAREHOUSE" size="mini">仓库</el-radio>
            <el-tooltip class="item" effect="dark" content="根据物料所在仓库等级进行拆分" placement="top-start">
              <i class="header-icon el-icon-info"></i>
            </el-tooltip>
            <span class="title">仓库拆分等级：</span>
            <el-select v-model="preMaterialRuleDialog.form.cangkuValue" placeholder="请选择仓库拆分等级" size="mini">
              <el-option v-for="item in preMaterialRuleDialog.form.cangkuLevelList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-row>

          <el-row class="ruleRowForm">
            <el-radio v-model="preMaterialRuleDialog.form.splitType" border label="PEOPLE" size="mini">人员</el-radio>
            <el-tooltip class="item" effect="dark" content="根据仓库等级所对应的负责人进行拆分" placement="top-start">
              <i class="header-icon el-icon-info"></i>
            </el-tooltip>
            <span class="title">仓库拆分等级：</span>
            <el-select v-model="preMaterialRuleDialog.form.renyuanValue" placeholder="请选择仓库拆分等级" size="mini">
              <el-option v-for="item in preMaterialRuleDialog.form.cangkuLevelList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </el-row>

          <el-row class="ruleRowForm">
            <el-radio v-model="preMaterialRuleDialog.form.splitType" border label="SECTION" size="mini">工段</el-radio>
            <el-tooltip class="item" effect="dark" content="ERP同步的领料单据有工段，比如SMT, DIP，组装等工段；按工段拆分" placement="top-start">
              <i class="header-icon el-icon-info"></i>
            </el-tooltip>
            <!-- <span class="title">工段：</span>
            <el-cascader v-model="sectionValue" :options="sectionOptions"></el-cascader> -->
          </el-row>

          <el-row class="ruleRowForm">
            <el-radio v-model="preMaterialRuleDialog.form.splitType" border label="PREPROCESS" size="mini">前加工</el-radio>
            <el-tooltip class="item" effect="dark" content="根据的工单产品所需前加工和非加工物料进行拆分 " placement="top-start">
              <i class="header-icon el-icon-info"></i>
            </el-tooltip>
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick type="primary" size="small" @click="saveRule" icon="el-icon-circle-plus-outline">保 存 </el-button>
        <el-button @click="cancelRule" size="small" icon="el-icon-circle-close">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增备料单 -->
    <add-dialog ref="add" :visible="addDialog.visible" @closeDialog="addDialog.visible = false" @generateSuccess="generateSuccess"></add-dialog>

    <!-- 欠料分析 -->
    <underfeed-analysis
      ref="underfeedAnalysis"
      :visible="underfeedAnalysisDialog.visible"
      @closeDialog="underfeedAnalysisDialog.visible = false"
      @unfeedGenerateSuccess="unfeedGenerateSuccess"
    ></underfeed-analysis>

    <!-- 合并撤销 -->
    <mergeUndo-dialog ref="mergeUndo" :undoData="selectionList" :visible="mergeUndoDialog.visible" @closeDialog="closeMergeUndoDialog()"></mergeUndo-dialog>

    <!-- 拆分撤销 -->
    <splitUndoDialog ref="splitUndo" :undoData="selectionList" :visible="splitUndoDialog.visible" @closeDialog="closeSplitUndoDialog()"></splitUndoDialog>

    <!-- 拆分备料单 -->
    <splitDialog ref="split" :visible="splitDialog.visible" @closeDialog="closeSplitDialog"></splitDialog>

    <!-- 备料单详情 -->
    <detailDialog ref="detail" :visible="detailDialog.visible" @closeDialog="detailDialog.visible = false"></detailDialog>

    <!-- 打印 -->
    <printDialog ref="print" :visible="printDialog.visible" @closeDialog="printDialog.visible = false"></printDialog>

    <!-- 导出 -->
    <export-comp ref="exportComp" page-api-url="mes-warehouse/preparation-order/page" :option="exportOptions" :page="page" :query="query" file-name="备料单"> </export-comp>

    <!-- 出库 -->
    <el-dialog
      custom-class="outBoundDialog"
      append-to-body
      :close-on-click-modal="false"
      title="备料出库"
      :visible.sync="outBoundDialog.visible"
      v-if="outBoundDialog.visible"
      width="90%"
      top="7vh"
      @close="outBoundClose"
    >
      <div class="formHeader">
        <div class="item">
          <div class="label">备料单号：</div>
          <div class="content">{{ selectionList[0].sheetNo }}</div>
        </div>
        <div class="item">
          <div class="label">关联领料单号：</div>
          <div class="content">{{ selectionList[0].pickSheetNoList }}</div>
        </div>
      </div>
      <avue-crud
        :option="outBoundDialog.option"
        :table-loading="outBoundDialog.loading"
        :data="outBoundDialog.tableData"
        :search.sync="outBoundDialog.search"
        :before-open="beforeOpen"
        v-model="outBoundDialog.form"
        ref="outBoundTableCrud"
        :key="timer"
      >
        <template slot="needOutboundQuantity" slot-scope="{ row }">
          <avue-input-number
            size="mini"
            v-model="row.needOutboundQuantity"
            :minRows="0"
            :maxRows="Number(row.pickedQuantity) - Number(row.completedQuantity)"
          ></avue-input-number>
        </template>
      </avue-crud>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" icon="el-icon-check" @click="handleOutboundSubmit">出库</el-button>
        <el-button size="small" icon="el-icon-delete" @click="handleReset">取消</el-button>
      </span>
    </el-dialog>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
  </basic-container>
</template>

<script>
import {
  submitRule,
  update,
  getList,
  getDetail,
  getMaterialInfoById,
  getSheetheaderPage,
  unfeedAnalysis,
  operationSubmit,
  outBound,
  getPrepareMaterialDetail
} from '@/api/warehouse/preMaterialList';
import { getAllSectionList } from '@/api/product/productStandardCapacity';
import exportComp from '@/components/export-comp';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
import { getPrinter } from '@/api/admin/barcode-record';

import addDialog from './addDialog.vue';
import underfeedAnalysis from './underfeedAnalysis.vue';
import printDialog from './printDialog.vue';
import splitDialog from './splitDialog.vue';
import detailDialog from './detailDialog.vue';
import mergeUndoDialog from './mergeUndoDialog.vue';
import splitUndoDialog from './splitUndoDialog.vue';

export default {
  name: 'PreMaterialList',
  components: {
    exportComp,
    userTableConfig,
    GlobalModalTemplate,
    addDialog,
    printDialog,
    splitDialog,
    detailDialog,
    mergeUndoDialog,
    splitUndoDialog,
    underfeedAnalysis
  },
  mixins: [userConfig()],
  data() {
    return {
      parentId: undefined,
      rowData: null,
      rowId: null,
      visibile: false,
      labelTemplateId: '',
      printerId: '',
      pageCode: 'BACKWASHRECORD',
      preMaterialRuleType: 'global', // 备料规则配置类型 全局:global/新增:add/拆分:split
      form: {},
      query: {},
      sheetForm: {},
      properties: {},
      loading: false,
      tableOption: {}, //模态框配置
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      showDialog: false,
      sectionValue: '',
      sectionOptions: [],
      data: [],
      option: {
        rowKey: 'id',
        calcHeight: 30,
        height: 'calc(100vh - 380px)',
        tip: false,
        searchShow: true,
        searchMenuPosition: 'right',
        searchMenuSpan: 4,
        dialogClickModal: false,
        searchLabelWidth: 80,
        border: true,
        viewBtn: false,
        addBtn: false,
        selection: true,
        reserveSelection: true,
        printBtn: false,
        editBtn: true,
        delBtn: false,
        searchSpan: 6,
        columnBtn: false,
        menuWidth: 250,
        lazy: true,
        column: [
          {
            label: '备料单号',
            prop: 'preparationOrderNo',
            overHidden: true,
            searchOrder: 2,
            search: true,
            editDisabled: true
          },
          {
            label: '工单号',
            prop: 'workOrderNos',
            searchOrder: 3,
            overHidden: true,
            search: true,
            editDisabled: true
          },
          {
            label: '产品编码',
            prop: 'productPartNos',
            overHidden: true,
            searchOrder: 4,
            search: true,
            editDisabled: true
          },
          {
            label: '产品型号',
            prop: 'productPartModels',
            overHidden: true,
            searchOrder: 5,
            search: true,
            editDisabled: true
          },
          {
            label: '部门',
            prop: 'deptName',
            width: 150,
            overHidden: true,
            searchOrder: 7,
            search: true,
            editDisabled: true
          },
          {
            label: '物料负责人',
            prop: 'supervisorName',
            width: 100,
            editDisabled: true
          },
          {
            label: '创建人',
            prop: 'createUserName',
            width: 100,
            editDisabled: true
          },
          {
            label: '创建时间',
            prop: 'createTime',
            width: 140,
            searchOrder: 1,
            search: true,
            searchType: 'datetimerange',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '开始时间',
            editDisabled: true
          },
          {
            label: '单据状态',
            prop: 'status',
            width: 80,
            type: 'select',
            searchOrder: 6,
            search: true,
            dicData: [
              { label: '待出库', value: 1 },
              { label: '部分出库', value: 2 },
              { label: '已完成', value: 3 },
              { label: '已拆分', value: 4 }
            ],
            editDisabled: true
          },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            span: 24,
            width: 150,
            overHidden: true,
            width: 200,
            rules: [
              {
                required: true,
                message: '请输入备注',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      preMaterialRuleDialog: {
        visible: false,
        activeName: 'first',
        form: {
          isFifo: true,
          isSpecifyAnalysis: false,
          specifyMaterialCategoryCodes: [],
          specifyMaterialCategoryAnalysisList: [],
          splitType: 'WAREHOUSE',
          cangkuValue: '',
          renyuanValue: '',
          cangkuLevelList: [
            { value: 1, label: 'L1' },
            { value: 2, label: 'L2' },
            { value: 3, label: 'L3' },
            { value: 4, label: 'L4' },
            { value: 5, label: 'L5' }
          ]
        }
      },
      addDialog: {
        visible: false
      },
      underfeedAnalysisDialog: {
        visible: false
      },
      printDialog: {
        visible: false
      },
      splitDialog: {
        visible: false
      },
      detailDialog: {
        visible: false
      },
      mergeUndoDialog: {
        visible: false
      },
      splitUndoDialog: {
        visible: false
      },
      operateRecordDialog: {
        visible: false
      },
      outBoundDialog: {
        visible: false,
        loading: false,
        tableData: [],
        search: {},
        formHeader: {
          bldh: '',
          gllldh: ''
        },
        form: {},
        page: {
          pageSize: 15,
          currentPage: 1,
          total: 0
        },
        option: {
          calcHeight: 30,
          height: 400,
          maxHeight: 400,
          tip: false,
          page: false,
          searchShow: true,
          searchMenuPosition: 'right',
          searchMenuSpan: 4,
          dialogClickModal: false,
          border: true,
          viewBtn: false,
          addBtn: false,
          selection: false,
          printBtn: false,
          editBtn: false,
          delBtn: false,
          index: false,
          searchSpan: 5,
          columnBtn: false,
          refreshBtn: false,
          searchBtn: false,
          emptyBtn: false,
          expandBtn: false,
          searchIcon: false,
          menu: false,
          column: [
            {
              label: '领料人',
              prop: 'picker',
              searchLabelWidth: 100,
              type: 'search',
              placeholder: '请扫领料人工卡条码',
              hide: true,
              search: true,
              searchRules: [
                {
                  required: false,
                  message: '请扫领料人工卡条码',
                  trigger: 'blur'
                }
              ],
              appendClick: () => {
                this.openUserCommonModal({
                  type: 'picker'
                });
              }
            },
            {
              label: '领料单号',
              prop: 'originalSheetNoStr',
              overHidden: true
            },
            {
              label: '工单号',
              prop: 'workOrderNoStr',
              overHidden: true
            },
            {
              label: '生产订单号',
              prop: 'productOrderNoStr',
              overHidden: true
            },
            {
              label: '物料名称',
              prop: 'partMasterName',
              overHidden: true
            },
            {
              label: '物料编码',
              prop: 'partNo',
              overHidden: true
            },
            {
              label: 'Bom版本',
              width: 80,
              prop: 'bomVersion'
            },
            {
              label: '需求数量',
              prop: 'requiredQuantity'
            },
            {
              label: '应发数量',
              prop: 'quantity'
            },
            {
              label: '已拣货数量',
              prop: 'pickedQuantity'
            },
            {
              label: '已发料数量',
              prop: 'completedQuantity'
            },
            {
              label: '状态',
              prop: 'status',
              width: 100,
              type: 'select',
              dicData: [
                { label: '已发料', value: 0 },
                { label: '待备料', value: 1 },
                { label: '发料中', value: 2 },
                { label: '备料中', value: 3 },
                { label: '待拣货', value: 4 },
                { label: '拣货中', value: 5 },
                { label: '待发料', value: 6 }
              ]
            },
            {
              label: '出库数量',
              prop: 'needOutboundQuantity',
              width: 150
            }
          ]
        }
      },
      modalName: '',
      timer: new Date().getTime() //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
    };
  },
  watch: {
    'preMaterialRuleDialog.form.splitType': {
      handler(value) {
        if (value == 'PEOPLE') {
          this.preMaterialRuleDialog.form.cangkuValue = '';
        } else if (value == 'WAREHOUSE') {
          this.preMaterialRuleDialog.form.renyuanValue = '';
        } else {
          this.preMaterialRuleDialog.form.cangkuValue = '';
          this.preMaterialRuleDialog.form.renyuanValue = '';
        }
      },
      deep: true
    }
  },
  async mounted() {
    // this.$nextTick(() => {
    //   this.$structuralSplit();
    // });
    // this.getAllSectionData();
    // const printer = await this.getDefaultPrinter();
    // const { labelTemplateId = '', printerId = '' } = printer;
    // this.labelTemplateId = labelTemplateId;
    // this.printerId = printerId;
  },
  computed: {
    ...mapGetters(['permission', 'userInfo']),
    permissionList() {
      return {
        // addBtn: this.vaildData(this.permission.pickingListManage_add, false),
        viewBtn: this.vaildData(this.permission.backWashRecord_view, false)
        // delBtn: this.vaildData(this.permission.pickingListManage_delete, false),
        // editBtn: this.vaildData(this.permission.pickingListManage_edit, false)
      };
    },
    exportOptions() {
      let exportOptions = structuredClone(this.option);
      exportOptions.column = exportOptions.column.filter((item) => {
        return item.prop != 'dataIndex';
      });
      return exportOptions;
    }
  },
  methods: {
    async getDefaultPrinter() {
      const { user_id } = this.userInfo;
      try {
        const res = await getPrinter({ id: user_id });
        return res.data.data;
      } catch (e) {
        console.warn(e);
      }
    },
    getAllSectionData() {
      getAllSectionList().then((res) => {
        let data = res.data.data;
        this.sectionOptions = data.map((item) => {
          let res = {
            label: item.name,
            value: item.id
          };
          if (item.childWorkSections && item.childWorkSections.length > 0) {
            res.children = item.childWorkSections.map((cItem) => {
              return {
                label: cItem.name,
                value: cItem.id
              };
            });
          }
          return res;
        });
      });
    },
    // 新增 给备料单 赋值 全局备料配置
    handleAdd() {
      this.addDialog.visible = true;
      this.$refs.add.addDialog.title = '新增备料单';
      this.$refs.add.rowData = null;
      // searchRule().then((res) => {
      //   let data = res.data.data;
      //   let prepareRuleData = data.find((d) => d.type == 1);
      //   if (prepareRuleData) {
      //     // let content = JSON.parse(prepareRuleData.content || '{}');
      //     let content = prepareRuleData.preparationAnalysisRuleDTO;
      //     this.preMaterialRuleDialog.form.isFifo = content.isFifo;
      //     this.$refs.add.isFifo = this.preMaterialRuleDialog.form.isFifo;
      //     this.$refs.add.specifyMaterialCategoryAnalysisList = content.specifyMaterialCategoryAnalysisList;
      //     if (content.specifyMaterialCategoryAnalysisList && content.specifyMaterialCategoryAnalysisList.length > 0) {
      //       this.$refs.add.isSpecifyAnalysis = true;
      //       this.$refs.add.specifyMaterialCategoryCodes = content.specifyMaterialCategoryAnalysisList.map((item) => item.categoryId);
      //     } else {
      //       this.$refs.add.isSpecifyAnalysis = false;
      //       this.$refs.add.specifyMaterialCategoryCodes = [];
      //     }
      //   }
      // });
      this.$refs.add.prepareMaterialSheetHeaderId = '';
      this.$refs.add.query = {};
      this.$refs.add.getDeptData(); // 获取部门数据
      // this.$refs.add.getLineSideData(); // 获取线边库数据
    },
    rowUpdate(form, index, done, loading) {
      update(form.id, form.remark).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.createTime && params.createTime.length > 1) {
        params.startTime = params.createTime[0];
        params.endTime = params.createTime[1];
        delete params.createTime;
      }
      this.query = params;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query))
        .then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          data.records.forEach((item, index) => {
            item.isLeaf = false;
            item.dataIndex = (data.current - 1) * data.size + index + 1;
            if (item.isSplit) {
              item.hasChildren = true;
            }
            // if (item.children && item.children.length > 0) {
            //   item.children.map((cItem, cIndex) => {
            //     cItem.dataIndex = item.dataIndex + '-' + (cIndex + 1);
            //   });
            // }
          });
          this.data = data.records;
          this.selectionClear();
        })
        .finally(() => {
          this.loading = false;
        });
    },
    treeLoad(tree, treeNode, resolve) {
      const parentId = tree.id;
      getList(this.page.currentPage, this.page.pageSize, Object.assign({ sourceId: parentId }, this.query)).then((res) => {
        let data = res.data.data;
        let records = data.records || [];
        records.forEach((item, index) => {
          item.isLeaf = true;
        });
        resolve(records);
      });
    },
    handleView(row) {
      this.detailDialog.visible = true;
      // this.$refs.detail.detailHeaderForm = structuredClone(row);
      this.$refs.detail.getData(row.id);
    },
    saveRule() {
      console.log(this.preMaterialRuleType);
      if (this.preMaterialRuleType == 'global') {
        let specifyMaterialCategoryAnalysisList = this.preMaterialRuleDialog.form.specifyMaterialCategoryAnalysisList.map((item) => {
          return {
            categoryId: item.categoryId,
            categoryName: item.categoryName,
            categoryCode: item.categoryCode
          };
        });
        let params = {
          analysisRuleDTO: {
            isFifo: this.preMaterialRuleDialog.form.isFifo,
            specifyMaterialCategoryAnalysisList
          },
          splitRuleDTO: {
            splitType: this.preMaterialRuleDialog.form.splitType,
            splitLevel: '',
            splitLevelValue: ''
          }
        };
        if (this.preMaterialRuleDialog.form.splitType == 'WAREHOUSE') {
          if (!this.preMaterialRuleDialog.form.cangkuValue) {
            this.$message.warning('请选择仓库拆分等级');
            return;
          }
          params.splitRuleDTO.splitLevelValue = Number(this.preMaterialRuleDialog.form.cangkuValue);
          let find = this.preMaterialRuleDialog.form.cangkuLevelList.find((list) => list.value == params.splitRuleDTO.splitLevelValue);
          if (find) {
            params.splitRuleDTO.splitLevel = find.label;
          }
        } else if (this.preMaterialRuleDialog.form.splitType == 'PEOPLE') {
          if (!this.preMaterialRuleDialog.form.renyuanValue) {
            this.$message.warning('请选择仓库拆分等级');
            return;
          }
          params.splitRuleDTO.splitLevelValue = Number(this.preMaterialRuleDialog.form.renyuanValue);
          let find = this.preMaterialRuleDialog.form.cangkuLevelList.find((list) => list.value == params.splitRuleDTO.splitLevelValue);
          if (find) {
            params.splitRuleDTO.splitLevel = find.label;
          }
        } else {
          params.splitRuleDTO.splitLevelValue = null;
          params.splitRuleDTO.splitLevel = null;
        }
        submitRule(params)
          .then((res) => {
            this.$message.success('备料规则配置成功');
            this.preMaterialRuleDialog.visible = false;
          })
          .catch((err) => {});
      } else if (this.preMaterialRuleType == 'add') {
        this.$message.success('备料规则配置成功');
        this.preMaterialRuleDialog.visible = false;
        this.$refs.add.isFifo = this.preMaterialRuleDialog.form.isFifo;
        this.$refs.add.specifyMaterialCategoryAnalysisList = this.preMaterialRuleDialog.form.specifyMaterialCategoryAnalysisList.map((item) => {
          return {
            categoryCode: item.categoryCode,
            categoryId: item.categoryId,
            categoryName: item.categoryName
          };
        });
        this.$refs.add.specifyMaterialCategoryCodes = this.preMaterialRuleDialog.form.specifyMaterialCategoryCodes;
        this.$refs.add.isSpecifyAnalysis = this.preMaterialRuleDialog.form.isSpecifyAnalysis;

        // 调用备料分析接口
        this.$refs.add.saveAnalysis();
      } else if (this.preMaterialRuleType == 'edit') {
        this.$message.success('备料规则配置成功');
        this.preMaterialRuleDialog.visible = false;
        this.$refs.add.isFifo = this.preMaterialRuleDialog.form.isFifo;
        this.$refs.add.specifyMaterialCategoryAnalysisList = this.preMaterialRuleDialog.form.specifyMaterialCategoryAnalysisList.map((item) => {
          return {
            categoryCode: item.categoryCode,
            categoryId: item.categoryId,
            categoryName: item.categoryName
          };
        });
        this.$refs.add.specifyMaterialCategoryCodes = this.preMaterialRuleDialog.form.specifyMaterialCategoryCodes;
        this.$refs.add.isSpecifyAnalysis = this.preMaterialRuleDialog.form.isSpecifyAnalysis;

        // 调用备料分析接口
        this.$refs.add.saveAnalysis();
      } else if (this.preMaterialRuleType == 'split') {
        if (this.preMaterialRuleDialog.form.splitType == 'WAREHOUSE') {
          if (!this.preMaterialRuleDialog.form.cangkuValue) {
            this.$message.warning('请选择仓库拆分等级');
            return;
          }
        }
        if (this.preMaterialRuleDialog.form.splitType == 'PEOPLE') {
          if (!this.preMaterialRuleDialog.form.renyuanValue) {
            this.$message.warning('请选择仓库拆分等级');
            return;
          }
        }
        this.$message.success('备料规则配置成功');
        this.preMaterialRuleDialog.visible = false;
        this.formatterSplitParams();
        this.$refs.split.getData(this.rowId);
      } else if (this.preMaterialRuleType == 'underfeed') {
        this.$message.success('备料规则配置成功');
        this.preMaterialRuleDialog.visible = false;

        this.$refs.underfeedAnalysis.isFifo = this.preMaterialRuleDialog.form.isFifo;
        this.$refs.underfeedAnalysis.specifyMaterialCategoryAnalysisList = this.preMaterialRuleDialog.form.specifyMaterialCategoryAnalysisList.map((item) => {
          return {
            categoryCode: item.categoryCode,
            categoryId: item.categoryId,
            categoryName: item.categoryName
          };
        });
        this.$refs.underfeedAnalysis.specifyMaterialCategoryCodes = this.preMaterialRuleDialog.form.specifyMaterialCategoryCodes;
        this.$refs.underfeedAnalysis.isSpecifyAnalysis = this.preMaterialRuleDialog.form.isSpecifyAnalysis;
        // 调用备料分析接口
        this.$refs.underfeedAnalysis.saveAnalysis();
      }
    },
    cancelRule() {
      this.preMaterialRuleDialog.visible = false;
    },
    handlePrint(row) {
      let name = row.isLeaf ? '子备料单' : '备料单';
      window.open(`${this.website.reportUrl}/preview?_u=blade-V86${name}打印.ureport.xml&=preparationOrderNo=${row.preparationOrderNo}`);
    },

    handleSplit(row) {
      this.rowId = row.id;
      this.rowData = structuredClone(row);
      this.splitDialog.visible = true;
      this.$refs.split.getData(row); // 获取拆分数据
    },
    // 新增成功
    generateSuccess() {
      this.addDialog.visible = false;
      this.selectionClear();
      this.onLoad(this.page);
    },
    // 欠料分析成功
    unfeedGenerateSuccess() {
      this.underfeedAnalysisDialog.visible = false;
      this.selectionClear();
      this.onLoad(this.page);
    },
    // 拆分备料单
    closeSplitDialog() {
      this.splitDialog.visible = false;
      this.selectionClear();
      // this.getGlobalRules();
      this.onLoad(this.page);
    },
    // 合并撤销
    closeMergeUndoDialog() {
      this.mergeUndoDialog.visible = false;
      this.selectionClear();
      this.onLoad(this.page);
    },
    // 拆分撤销
    closeSplitUndoDialog() {
      this.splitUndoDialog.visible = false;
      this.selectionClear();
      this.onLoad(this.page);
    },
    formatterSplitParams() {
      this.$refs.split.isFifo = this.preMaterialRuleDialog.form.isFifo;
      this.$refs.split.splitType = this.preMaterialRuleDialog.form.splitType;
      if (this.preMaterialRuleDialog.form.splitType == 'WAREHOUSE') {
        this.$refs.split.splitLevelValue = Number(this.preMaterialRuleDialog.form.cangkuValue);
        let find = this.preMaterialRuleDialog.form.cangkuLevelList.find((list) => list.value == Number(this.preMaterialRuleDialog.form.cangkuValue));
        if (find) {
          this.$refs.split.splitLevel = find.label;
        }
      } else if (this.preMaterialRuleDialog.form.splitType == 'PEOPLE') {
        this.$refs.split.splitLevelValue = Number(this.preMaterialRuleDialog.form.renyuanValue);
        let find = this.preMaterialRuleDialog.form.cangkuLevelList.find((list) => list.value == Number(this.preMaterialRuleDialog.form.renyuanValue));
        if (find) {
          this.$refs.split.splitLevel = find.label;
        }
      } else {
        this.$refs.split.splitLevelValue = null;
        this.$refs.split.splitLevel = null;
      }
    },
    // 出库 发料中，待发料时，才能出库
    handleOutBound() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return false;
      }
      // let sheetNoArray = this.selectionList.map((item) => item.sheetNo);
      // let isRepeatData = this.hasDuplicates(sheetNoArray);
      if (this.selectionList.length > 1) {
        this.$message.warning('此功能不支持批量处理，只能选择一条数据');
        return false;
      }

      // let isAllowOutBound = this.selectionList.every((list) => {
      //   return list.status == 2 || list.status == 6;
      // });
      // if (!isAllowOutBound) {
      //   this.$message.warning('领料单状态为发料中或待发料的才能进行出库！');
      //   return false;
      // }
      console.log(this.selectionList, 'this.selectionList');
      this.outBoundDialog.visible = true;
      getPrepareMaterialDetail(this.selectionList[0].id)
        .then((res) => {
          let data = res.data.data;
          data.forEach((item) => {
            item.needOutboundQuantity = Number(item.pickedQuantity) - Number(item.completedQuantity);
          });
          this.outBoundDialog.tableData = data;
          // this.outBoundDialog.page.total = data.total;
        })
        .catch((err) => {});
    },
    openUserCommonModal(params) {
      let { type } = params;
      switch (type) {
        // 领料人
        case 'picker':
          this.modalName = 'pickerModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择用户管理信息（双击进行选择）',
            url: '/api/blade-user/page',
            isPage: true,
            rowSelectionType: 'single',
            menuWidth: 100,
            templateName: 'USER'
          };
          break;
        // 物料类别
        case 'materialCategory':
          this.modalName = 'partcategoryModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择物料类别（双击进行选择）',
            url: '/api/mes-admin/partcategory/lazy-list-page',
            query: {
              parentId: 0
            },
            lazyTreeUrl: '/api/mes-admin/partcategory/lazy-list',
            tree: true,
            lazy: true, // 懒加载
            isPage: true,
            rowSelectionType: 'multiple',
            menuWidth: 100,
            templateName: 'PARTCATEGORY'
          };
          break;
        default:
          break;
      }
    },
    // 获取选择的模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'pickerModal':
          // this.outBoundDialog.form.picker = this._get(rowData, 'id', '');
          this.outBoundDialog.search.picker = this._get(rowData, 'realName', '');
          break;
        case 'partcategoryModal':
          this.preMaterialRuleDialog.form.specifyMaterialCategoryAnalysisList = rowData.map((item) => {
            return {
              categoryId: item.id + '',
              categoryName: item.name,
              categoryCode: item.code,
              value: item.id + '',
              label: item.code
            };
          });
          this.preMaterialRuleDialog.form.specifyMaterialCategoryCodes = this.preMaterialRuleDialog.form.specifyMaterialCategoryAnalysisList.map((item) => item.value);
          console.log(this.preMaterialRuleDialog.form.specifyMaterialCategoryAnalysisList, 'rowData');
          break;
        default:
          break;
      }
    },
    handleOutboundSubmit() {
      let inventoryItemList = this.outBoundDialog.tableData.map((item) => {
        return {
          sheetDetailId: item.id,
          sheetHeaderId: item.sheetHeaderId,
          partMasterId: item.partMasterId,
          quantity: item.needOutboundQuantity
        };
      });
      let isValidQuantity = inventoryItemList.every((item) => item.quantity > 0);
      if (!isValidQuantity) {
        this.$message.warning('提交数据中存在出库数量为0的数据，请仔细检查');
        return false;
      }
      let params = {
        actCode: 'prepare-outBound-activity',
        requestParams: {
          type: 'INVENTORY_TRANSACTION',
          transactionType: 'OUTBOUND',
          sheetType: 'MPL',
          sheetId: this.selectionList[0].id,
          sheetNo: this.selectionList[0].sheetNo,
          equipmentId: this.printerId,
          labelTemplateId: this.labelTemplateId,
          inventoryItemList
        }
      };
      outBound(params)
        .then((res) => {
          this.$message.success('出库成功');
          this.outBoundDialog.visible = false;
          this.onLoad(this.page);
          this.selectionClear();
        })
        .catch((err) => {});
    },
    handleReset() {
      this.outBoundDialog.visible = false;
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },
    handleAddMaterial() {
      this.openUserCommonModal({
        type: 'materialCategory'
      });
    },
    handleChangeSpecifyAnalysis(value) {
      if (!value) {
        this.preMaterialRuleDialog.form.specifyMaterialCategoryCodes = [];
        this.preMaterialRuleDialog.form.specifyMaterialCategoryAnalysisList = [];
      }
    },
    handleSpecifyMaterialCategoryDelete(values) {
      this.preMaterialRuleDialog.form.specifyMaterialCategoryAnalysisList = this.preMaterialRuleDialog.form.specifyMaterialCategoryAnalysisList.filter((item) => {
        return values.includes(item.categoryId);
      });
      let len = this.preMaterialRuleDialog.form.specifyMaterialCategoryAnalysisList.length;
      if (len == 0) {
        this.$set(this.preMaterialRuleDialog.form, 'isSpecifyAnalysis', false);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .ruleDialog {
  .avue-crud__menu {
    display: none;
  }
  .ruleRowForm {
    margin-bottom: 5px;
    .el-radio {
      margin-right: 10px;
    }
    .header-icon {
      margin-right: 10px;
    }
    .title {
      width: 100px;
      text-align: right;
      display: inline-block;
    }
  }
  .item {
    .specifyAnalysis {
      // margin: 8px 0;
      height: 40px;
      display: flex;
      align-items: center;
      .addMaterialBtn {
        margin-left: 5px;
      }
    }
  }
}
::v-deep .outBoundDialog {
  .formHeader {
    display: flex;
    margin-bottom: 10px;
    .item {
      display: flex;
      align-items: center;
      &:first-child {
        margin-right: 50px;
      }
      .label {
        width: 100px;
        white-space: nowrap;
        text-align: right;
        padding-right: 12px;
        box-sizing: border-box;
      }
    }
  }
  .avue-crud__menu {
    display: none;
  }
}
::v-deep .specifyMaterialCategoryAnalysisSelect .el-input__suffix {
  display: none;
}
</style>
